package com.gxa.listener;

import com.gxa.order.pojo.PayLog;
import com.gxa.order.pojo.TxLog;
import com.gxa.repository.TxLogRepository;
import com.gxa.service.impl.PayServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

@Slf4j
@RocketMQTransactionListener(txProducerGroup="tx-pay-group")
public class PayListener implements RocketMQLocalTransactionListener {

    @Autowired
    private TxLogRepository txLogRepository;

    @Autowired
    private PayServiceImpl payService;

    //监听半成品消息是否发送成功，如果发送成功RocketMq执行此方法
    //执行本地事物
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object obj) {
        try {
            payService.createPayLog((PayLog)obj,(String) message.getHeaders().get("txId"));
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            log.error("exception:{}",e.getMessage());
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    //消息回查  rocketMq没有收到确认消息
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //查询日志记录
        TxLog txLog = txLogRepository.findById((String) message.getHeaders().get("txId")).get();
        if(txLog==null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }else{
            return RocketMQLocalTransactionState.COMMIT;
        }

    }

}
